#coding=utf-8
#Boa:Dialog:DlgVoucher

import wx
import wx.grid

from config import *
from product import *
from ctrlAider import *

def create(parent):
    return DlgVoucher(parent)

[wxID_DLGVOUCHER, wxID_DLGVOUCHERBTNCANCEL, wxID_DLGVOUCHERBTNOK, 
 wxID_DLGVOUCHERBTNSHOWPEER, wxID_DLGVOUCHERCBPAYWAY, wxID_DLGVOUCHERCBSTAFF, 
 wxID_DLGVOUCHERDATEBILL, wxID_DLGVOUCHERGRID, wxID_DLGVOUCHERSTATICTEXT1, 
 wxID_DLGVOUCHERSTATICTEXT2, wxID_DLGVOUCHERTCDEBT, wxID_DLGVOUCHERTCMEMO, 
 wxID_DLGVOUCHERTCMONEY, wxID_DLGVOUCHERTCPARTNER, 
 wxID_DLGVOUCHERTCUNALLOCATED, wxID_DLGVOUCHERTCVOUCHERID, 
 wxID_DLGVOUCHERTDATE, wxID_DLGVOUCHERTDEBT, wxID_DLGVOUCHERTMEMO, 
 wxID_DLGVOUCHERTMONEY, wxID_DLGVOUCHERTPARTNER, wxID_DLGVOUCHERTPAYWAY, 
 wxID_DLGVOUCHERTSTAFF, wxID_DLGVOUCHERTVOUCHERID, 
] = [wx.NewId() for _init_ctrls in range(24)]

[Type_Customer, Type_Supplier] = [i for i in range(2)]

class DlgVoucher(wx.Dialog):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Dialog.__init__(self, id=wxID_DLGVOUCHER, name=u'DlgVoucher',
              parent=prnt, pos=wx.Point(289, 59), size=wx.Size(872, 662),
              style=wx.DEFAULT_DIALOG_STYLE, title=u'\u4f1a\u6b3e\u5355')
        self.SetClientSize(wx.Size(864, 628))
        self.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False,
              u'\u6977\u4f53_GB2312'))
        self.SetBackgroundColour(wx.Colour(183, 209, 173))

        self.tcPartner = wx.TextCtrl(id=wxID_DLGVOUCHERTCPARTNER,
              name=u'tcPartner', parent=self, pos=wx.Point(176, 72),
              size=wx.Size(208, 24), style=0, value=u'')

        self.tPartner = wx.StaticText(id=wxID_DLGVOUCHERTPARTNER,
              label=u'\u9009\u62e9\u5ba2\u6237\uff1a', name=u'tPartner',
              parent=self, pos=wx.Point(88, 80), size=wx.Size(85, 16), style=0)

        self.tDebt = wx.StaticText(id=wxID_DLGVOUCHERTDEBT,
              label=u'\u603b\u6b20\u6b3e\uff1a', name=u'tDebt', parent=self,
              pos=wx.Point(88, 136), size=wx.Size(68, 16), style=0)

        self.tcMoney = wx.TextCtrl(id=wxID_DLGVOUCHERTCMONEY, name=u'tcMoney',
              parent=self, pos=wx.Point(176, 168), size=wx.Size(128, 24),
              style=0, value=u'')

        self.tMoney = wx.StaticText(id=wxID_DLGVOUCHERTMONEY,
              label=u'\u6536\u6b3e\u91d1\u989d\uff1a', name=u'tMoney',
              parent=self, pos=wx.Point(88, 176), size=wx.Size(85, 16),
              style=0)

        self.tMemo = wx.StaticText(id=wxID_DLGVOUCHERTMEMO,
              label=u'\u5907\u6ce8\u4fe1\u606f\uff1a', name=u'tMemo',
              parent=self, pos=wx.Point(88, 488), size=wx.Size(85, 16),
              style=0)

        self.tcMemo = wx.TextCtrl(id=wxID_DLGVOUCHERTCMEMO, name=u'tcMemo',
              parent=self, pos=wx.Point(184, 480), size=wx.Size(448, 24),
              style=0, value=u'')

        self.tStaff = wx.StaticText(id=wxID_DLGVOUCHERTSTAFF,
              label=u'\u7ecf\u529e\u4eba\uff1a', name=u'tStaff', parent=self,
              pos=wx.Point(416, 216), size=wx.Size(72, 14), style=0)

        self.cbStaff = wx.ComboBox(choices=[], id=wxID_DLGVOUCHERCBSTAFF,
              name=u'cbStaff', parent=self, pos=wx.Point(496, 208),
              size=wx.Size(138, 24), style=0, value=u'')

        self.tPayWay = wx.StaticText(id=wxID_DLGVOUCHERTPAYWAY,
              label=u'\u6536\u6b3e\u65b9\u5f0f\uff1a', name=u'tPayWay',
              parent=self, pos=wx.Point(88, 216), size=wx.Size(85, 16),
              style=0)

        self.tDate = wx.StaticText(id=wxID_DLGVOUCHERTDATE,
              label=u'\u65e5\u671f\uff1a', name=u'tDate', parent=self,
              pos=wx.Point(416, 176), size=wx.Size(64, 14), style=0)

        self.tVoucherId = wx.StaticText(id=wxID_DLGVOUCHERTVOUCHERID,
              label=u'\u5355\u53f7\uff1a', name=u'tVoucherId', parent=self,
              pos=wx.Point(416, 136), size=wx.Size(64, 14), style=0)

        self.tcVoucherId = wx.StaticText(id=wxID_DLGVOUCHERTCVOUCHERID,
              label=u'P(GK)F-20140516-0001', name=u'tcVoucherId', parent=self,
              pos=wx.Point(496, 136), size=wx.Size(180, 16), style=0)

        self.dateBill = wx.DatePickerCtrl(id=wxID_DLGVOUCHERDATEBILL,
              name=u'dateBill', parent=self, pos=wx.Point(496, 168),
              size=wx.Size(136, 22), style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)
        self.dateBill.SetLabel(u'2013-11-27')
        self.dateBill.SetValue(wx.DateTimeFromDMY(27, 10, 2013, 0, 0, 0))
        self.dateBill.SetWindowVariant(wx.WINDOW_VARIANT_NORMAL)
        self.dateBill.Bind(wx.EVT_DATE_CHANGED, self.OnDateBillDateChanged,
              id=wxID_DLGVOUCHERDATEBILL)

        self.cbPayWay = wx.ComboBox(choices=[], id=wxID_DLGVOUCHERCBPAYWAY,
              name=u'cbPayWay', parent=self, pos=wx.Point(176, 208),
              size=wx.Size(130, 24), style=0, value=u'')
        self.cbPayWay.SetLabel(u'')

        self.btnOK = wx.Button(id=wxID_DLGVOUCHERBTNOK, label=u'\u786e\u5b9a',
              name=u'btnOK', parent=self, pos=wx.Point(248, 512),
              size=wx.Size(75, 24), style=0)
        self.btnOK.Bind(wx.EVT_BUTTON, self.OnBtnOKButton,
              id=wxID_DLGVOUCHERBTNOK)

        self.btnCancel = wx.Button(id=wxID_DLGVOUCHERBTNCANCEL,
              label=u'\u53d6\u6d88', name=u'btnCancel', parent=self,
              pos=wx.Point(384, 512), size=wx.Size(75, 24), style=0)
        self.btnCancel.Bind(wx.EVT_BUTTON, self.OnBtnCancelButton,
              id=wxID_DLGVOUCHERBTNCANCEL)

        self.btnShowPeer = wx.Button(id=wxID_DLGVOUCHERBTNSHOWPEER, label=u'+',
              name=u'btnShowPeer', parent=self, pos=wx.Point(384, 72),
              size=wx.Size(24, 26), style=0)
        self.btnShowPeer.Bind(wx.EVT_BUTTON, self.OnBtnShowPeerButton,
              id=wxID_DLGVOUCHERBTNSHOWPEER)

        self.tcDebt = wx.TextCtrl(id=wxID_DLGVOUCHERTCDEBT, name=u'tcDebt',
              parent=self, pos=wx.Point(176, 128), size=wx.Size(128, 24),
              style=0, value=u'0.0')
        self.tcDebt.SetEditable(False)
        self.tcDebt.Enable(False)

        self.staticText1 = wx.StaticText(id=wxID_DLGVOUCHERSTATICTEXT1,
              label=u'\u9009\u62e9\u6307\u5b9a\u5355\u636e\uff1a',
              name='staticText1', parent=self, pos=wx.Point(88, 256),
              size=wx.Size(119, 16), style=0)

        self.staticText2 = wx.StaticText(id=wxID_DLGVOUCHERSTATICTEXT2,
              label=u'\u672a\u5206\u914d\u91d1\u989d\uff1a', name='staticText2',
              parent=self, pos=wx.Point(416, 256), size=wx.Size(102, 16),
              style=0)

        self.tcUnallocated = wx.TextCtrl(id=wxID_DLGVOUCHERTCUNALLOCATED,
              name=u'tcUnallocated', parent=self, pos=wx.Point(528, 248),
              size=wx.Size(104, 24), style=0, value=u'')
        self.tcUnallocated.SetEditable(False)
        self.tcUnallocated.Enable(False)

        self.grid = wx.grid.Grid(id=wxID_DLGVOUCHERGRID, name=u'grid',
              parent=self, pos=wx.Point(88, 280), size=wx.Size(544, 192),
              style=0)

    def __init__(self, parent, type):
        self._init_ctrls(parent)
        
        self.curType = type
        if(type == Type_Customer):
            self.ClsPeer = CDataCustomer
            self.ClsOrder = CDataSaleOrder
            self.ClsVoucher = CDataVoucher
            self.ClsFund = CRelFundCustomer
            
            self.pWin = DlgCustomerChoice.create(self)
            self.tcPeer = MyPopupTextCtrlDecorator(self.tcPartner, self.pWin)
            
        elif(type == Type_Supplier):
            self.ClsPeer = CDataSupplier
            self.ClsOrder = CDataPurOrder
            self.ClsVoucher = CDataVoucherSupplier
            self.ClsFund = CRelFundSupplier
            
            self.pWin = DlgCustomerChoice.create(self)
            self.tcPeer = MyPopupTextCtrlDecorator(self.tcPartner, self.pWin)
            
        self.myInit()
    
    def myInit(self):
        # empty means voucher for no spc bill
        self.billId = ''
        
        self.dateBill.SetValue(wx.DateTime.Today())
        self.refreshId()
        
        self.cb = MyComboBoxDecorator(self.cbPayWay, CDataAccount, CDataAccount.COL_BRIEFNAME)
        self.cb.refresh()
        self.cb.SetValue(CDataAccount.getDefAccount())
        
        self.cbHandler = MyComboBoxDecorator(self.cbStaff, CDataStaff, CDataStaff.COL_NAME)
        self.cbHandler.refresh()
        self.cbHandler.SetValue(Cfg.getCurUser().getValue(CDataStaff.COL_NAME))
        
        self.initState()
        
        self.initGrid()
    
    def initState(self):
        self.STATE_NEW = 0
        self.STATE_MODIFY = 1
        self.curState = self.STATE_NEW
        
        self.preVoucherId = ''
    
    def initGrid(self):
        titles = [(u'单据编号', 160), 
                    (u'总金额', 70), 
                    (u'已付', 70), 
                    (u'优惠',70), 
                    (u'未付',70),
                    (u'分配金额',80)]
        [self.COL_BILLID , self.COL_TOTAL, self.COL_PAID, self.COL_DISCOUNT,
        self.COL_UNPAID, self.COL_ALLOCT] = [i for i in range(len(titles))]
        
        self.grid.SetColLabelSize(32)
        self.grid.SetRowLabelSize(20)
         
        self.grid.CreateGrid(1, len(titles))
        for i in range(len(titles)):
            self.grid.SetColLabelValue(i, titles[i][0])
            self.grid.SetColSize(i, titles[i][1])
        
    def refreshId(self):
        date = self.dateBill.GetValue().Format('%Y%m%d')
        self.tcVoucherId.SetLabel(self.ClsVoucher.newBillId(date))
            
    def getBillObj(self, billId):
        return self.ClsOrder.getFirstInstance({self.ClsOrder.COL_ID:billId})
    
    def getVoucherObj(self, id):
        return self.ClsVoucher.getFirstInstance({self.ClsVoucher.COL_ID:id})
    
    def getPeerObj(self, billObj=None, voucherObj=None):
        if (billObj is not None):
            peerId = billObj.getValue(billObj.COL_PEERID)
        else:
            peerId = voucherObj.getValue(voucherObj.COL_PEERID)
            
        return self.ClsPeer.getFirstInstance({self.ClsPeer.COL_ID:peerId})
    
    
    def getMoney(self):
        return float(self.tcMoney.GetValue())
    
    def setEditData(self, voucherId):
        self.curState = self.STATE_MODIFY
        self.voucherObj = self.getVoucherObj(voucherId)
        
        # chk if related to order bill
        voucherObj = self.voucherObj
        billIds = voucherObj.getBillId()
                
        self.peerObj = self.getPeerObj(voucherObj=voucherObj)
        peerName = self.peerObj.getValue(self.peerObj.COL_NAME)
        
        money = voucherObj.getValue(voucherObj.COL_MONEY)
        memo = voucherObj.getValue(voucherObj.COL_MEMO)
                
        date = voucherObj.getValue(voucherObj.COL_DATE)
        if (isinstance(date, str) or isinstance(date, unicode)):
            import datetime
            date = datetime.datetime.strptime(date, '%Y-%m-%d')
        dateTime = wx.DateTimeFromDMY(date.day, date.month-1, date.year,0,0,0)
        
        hId = voucherObj.getValue(voucherObj.COL_HANDLERID)
        hObj = CDataStaff.getFirstInstance({CDataStaff.COL_ID:hId})
        hName = hObj.getValue(CDataStaff.COL_NAME)
        
        accountId = voucherObj.getValue(voucherObj.COL_ACCOUNTID)
        accountObj = CDataAccount.getFirstInstance({CDataAccount.COL_ID:accountId})
        accountName = accountObj.getValue(CDataAccount.COL_BRIEFNAME)
        
        if (billIds):
            self.tcBillId.SetLabel(billIds[0])
        else:
            self.tcBillId.Show(False)
            self.tBillId.Show(False)
            
        self.tcDebt.Show(False)
        self.tDebt.Show(False)
        
        self.tcVoucherId.SetLabel(voucherId)
        self.dateBill.SetValue(dateTime)
        self.cb.SetValue(accountName)
        self.cbHandler.SetValue(hName)
        self.tcPartner.SetValue(peerName)
        #self.tcDebt.SetLabel(str(debt))
        self.tcMoney.SetValue(str(money))
        self.tcMemo.SetValue(memo)
                
        self.tcMoney.SetInsertionPointEnd()
        self.tcMoney.SetSelection(-1, -1)
        self.tcMoney.SetFocus()
        
    def setData(self, billId='', peerObj = None):

        self.billObj = self.getBillObj(billId)
        
        if(peerObj is not None):
            self.peerObj = peerObj
        else:
            # peerObj is None, then billId must not be ''
            self.peerObj = self.getPeerObj(self.billObj)
            
        #self.peerObj = self.getPeerObj(self.billObj)
        peerName = self.peerObj.getValue(self.peerObj.COL_NAME)
        self.tcPartner.SetValue(peerName)

        if(self.billObj is not None):
            msg = u'是否针对<%s>付款\n'\
                    u'--选是，为该付款单付款\n'\
                    u'--选否，为<%s>付款' %(billId, peerName)
            dlg = wx.MessageDialog(self, msg,
                                    u'提示', wx.YES_NO|wx.ICON_QUESTION)
            
            if(dlg.ShowModal() == wx.ID_NO):
                self.billObj = None
                self.tBillId.Show(False)
                self.tcBillId.Show(False)
                
        if(self.billObj is None):
            debt = self.peerObj.getDebt()
        else:
            debt = self.billObj.getUnpaid()
            memo = u'为%s收款' %(billId)
            self.tcMemo.SetValue(memo)
        
        # view
        self.tcBillId.SetLabel(billId)
        self.tcDebt.SetLabel(str(debt))
        self.tcMoney.SetValue(str(debt))
                
        self.tcMoney.SetInsertionPointEnd()
        self.tcMoney.SetSelection(-1, -1)
        self.tcMoney.SetFocus()
    
    def saveFund(self):
        voucherId =  self.tcVoucherId.GetLabel()
        billId =  self.tcBillId.GetLabel()
        
        data = {self.ClsFund.COL_BILLID:billId, 
                self.ClsFund.COL_VOUCHERID:voucherId, 
                self.ClsFund.COL_MONEY:self.getMoney()}
        obj = self.ClsFund()
        obj.setMulFieldVal(data)
        obj.insert()
    
    def saveVoucher(self):
        id = self.tcVoucherId.GetLabel()
        custId = self.peerObj.getValue(self.peerObj.COL_ID)
        
        accountObj = self.cb.getSelectObj()
        accountId = accountObj.getValue(CDataAccount.COL_ID)
        
        money = float(self.tcMoney.GetValue())
        date = self.dateBill.GetValue().Format('%Y-%m-%d') 
        handlerId = self.cbHandler.getSelectObj().getValue(CDataStaff.COL_ID)
        recorderID = Cfg.getCurUser().getValue(CDataStaff.COL_ID)      
        memo = self.tcMemo.GetValue()
        
        data = {self.ClsVoucher.iId:id, 
                self.ClsVoucher.iPeerId:custId, 
                self.ClsVoucher.iAccountId:accountId,
                self.ClsVoucher.iMoney:money, 
                self.ClsVoucher.iDate:date, 
                self.ClsVoucher.iHandlerId:handlerId,
                self.ClsVoucher.iRecorderId:recorderID, 
                self.ClsVoucher.iMemo:memo}
        obj = self.ClsVoucher()
        obj.setMulFieldVal(data)
        obj.insert()
                      
    def OnDateBillDateChanged(self, event):
        self.refreshId()

    def OnBtnOKButton(self, event):
        if(self.curState == self.STATE_MODIFY):
            self.voucherObj.delete()
            
        self.saveVoucher()
        if (self.tBillId.IsShown()):
            self.saveFund()
            
        self.EndModal(wx.ID_OK)

    def OnBtnCancelButton(self, event):
        self.EndModal(wx.ID_CANCEL)

    def OnBtnShowPeerButton(self, event):
        event.Skip()
                
